//
//  LoginViewController.m
//  Growth
//
//  Created by Hobo.Chen on 12/30/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import"RegistViewController.h"
#import "WebRequest.h"
#import "WebConnetionArray.h"

#import "GrowthAppDelegate.h"


#import "CJSONSerializer.h"
#import "WebRequest.h"
#import "WebConnection.h"

static WebConnection *loginConnection;

static WebConnectionArray *timeline_Connection;

static WebConnectionArray *createNewUser_Connection;

static WebConnectionArray *bindUser_Connection;


@interface LoginViewController (Private)


@end


@implementation LoginViewController

@synthesize delegate;

@synthesize loginIDtextField;
@synthesize loginkeytextField;

@synthesize  oauthType;
@synthesize qq_userInfo_dict;

@synthesize weiBoEngine;

@synthesize weibo_userInfo_dict;

@synthesize backGroundButton;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewWillAppear:(BOOL)animated{
    
    
    [self navigationBarInit];
    [super viewWillAppear:YES];
    
    
}

- (void)viewDidLoad {
    
    oauthType = 0;  //非第三方登陆
    //显示上一次登陆的账号
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"email"]) {
        loginIDtextField.text=[[NSUserDefaults standardUserDefaults] valueForKey:@"email"];
        self.loginIDtextField.textColor = [UIColor blackColor];
    }
    
     self.contentView.backgroundColor = BackGround_Color;
    
       [backGroundButton setShowsTouchWhenHighlighted:NO];
       [backGroundButton setTintColor:[UIColor whiteColor]];
     
        backGroundButton.backgroundColor = [UIColor clearColor]; 

    
       [super viewDidLoad];
}



#pragma mark --
#pragma mark 用第三方建新账号

-(void)createNewQQUser:(NSString *)nickName{ 
    
    if (self.oauthType == 2) { //qq
        
        NSString *userName = nickName;
        NSString *userPhoto = [self.qq_userInfo_dict objectForKey:@"figureurl_2"];
        NSString *gender = [self.qq_userInfo_dict objectForKey:@"gender"];
        
        CLog(@"qq_usrinfoDict %@", qq_userInfo_dict);
        
        NSString *theBodyString = [NSString stringWithFormat:@"{\"platformId\":%d,\"accessToken\":\"%@\",\"nickname\":\"%@\",\"photo\":\"%@\",\"gender\":\"%@\"}",self.oauthType,_tencentOAuth.openId,userName,userPhoto,gender];
        
        
        //   NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
        CLog(@"theBodyString  %@", theBodyString);
        
        
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableURLRequest *request_derectIn = [WebRequest registBindingNewWith:_jsonData];
        
        createNewUser_Connection = [[WebConnectionArray alloc] initWith:request_derectIn delegate:self dataBaseListName:nil];

    }
    
    if (self.oauthType == 1) { //weibo
        
        NSString *userName = nickName;

        NSString *userPhoto = [self.weibo_userInfo_dict objectForKey:@"profile_image_url"];
        NSString *gender = [self.weibo_userInfo_dict objectForKey:@"gender"];
        
        CLog(@"qq_usrinfoDict %@", weibo_userInfo_dict);
        NSString *token = [self.weibo_userInfo_dict objectForKey:@"id"];

        
        NSString *theBodyString = [NSString stringWithFormat:@"{\"platformId\":%d,\"accessToken\":\"%@\",\"nickname\":\"%@\",\"photo\":\"%@\",\"gender\":\"%@\"}",self.oauthType,token,userName,userPhoto,gender];
        
        
        //   NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
        CLog(@"theBodyString  %@", theBodyString);
       
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableURLRequest *request_derectIn = [WebRequest registBindingNewWith:_jsonData];
        
       createNewUser_Connection = [[WebConnectionArray alloc] initWith:request_derectIn delegate:self dataBaseListName:nil];

    }
       

    
}



#pragma mark --
#pragma mark 第三方绑定已有账号

-(void)bindQQUser:(NSString *)email key:(NSString *)pass{
    
    if (self.oauthType == 2) { //qq
        
        NSString *userName = [self.qq_userInfo_dict objectForKey:@"nickname"];
        NSString *userPhoto = [self.qq_userInfo_dict objectForKey:@"figureurl_2"];
        NSString *gender = [self.qq_userInfo_dict objectForKey:@"gender"];
       
        CLog(@"qq_usrinfoDict %@", qq_userInfo_dict);
        
        NSString *theBodyString = [NSString stringWithFormat:@"{\"platformId\":%d,\"accessToken\":\"%@\",\"nickname\":\"%@\",\"photo\":\"%@\",\"gender\":\"%@\",\"email\":\"%@\",\"password\":\"%@\"}",self.oauthType,_tencentOAuth.openId,userName,userPhoto,gender,email,pass];
        
        
        CLog(@"theBodyString  %@", theBodyString);
        
        
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableURLRequest *request_derectIn = [WebRequest BindingExitWith:_jsonData];
        
        bindUser_Connection = [[WebConnectionArray alloc] initWith:request_derectIn delegate:self dataBaseListName:nil];
        

        
    }
    if (self.oauthType ==1) { //weibo
        
        NSString *userName = [self.weibo_userInfo_dict objectForKey:@"name"];
        NSString *userPhoto = [self.weibo_userInfo_dict objectForKey:@"profile_image_url"];
        NSString *gender = [self.weibo_userInfo_dict objectForKey:@"gender"];
        
        CLog(@"qq_usrinfoDict %@", weibo_userInfo_dict);
        NSString *token = [self.weibo_userInfo_dict objectForKey:@"id"];
        
        
        NSString *theBodyString = [NSString stringWithFormat:@"{\"platformId\":%d,\"accessToken\":\"%@\",\"nickname\":\"%@\",\"photo\":\"%@\",\"gender\":\"%@\",\"email\":\"%@\",\"password\":\"%@\"}",self.oauthType,token,userName,userPhoto,gender,email,pass];
        
        
        CLog(@"theBodyString  %@", theBodyString);
        
        
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableURLRequest *request_derectIn = [WebRequest BindingExitWith:_jsonData];
        
       bindUser_Connection = [[WebConnectionArray alloc] initWith:request_derectIn delegate:self dataBaseListName:nil];
        

        
    }
    
      
}


#pragma mark 验证token

-(void)verifyToken{
  
    NSString *token = [[NSString alloc]init];
    
    if (self.oauthType == 1) { // sina
        token = [weibo_userInfo_dict objectForKey:@"id"];
        
    }
    
    else if(self.oauthType == 2){ //qq 
        token = _tencentOAuth.openId;
        
    }

    NSMutableURLRequest * request = [WebRequest verifyTokenWith:token platformId:oauthType];
    WebConnectionArray *qq_tokenVerifyConnection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    
    
}

#pragma mark 公开验证
-(void)openCheck:(NSString *)token{
    
    NSMutableURLRequest *request = [RequestAPIExample login_openRequestWithUsr:token pwd:@"123456"];
    
    [request setHTTPShouldHandleCookies:YES];
    [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

    
    
}

#pragma mark 绑定页面

-(void)loadThirdPartView{
    
    if (self.oauthType == 1) { //weibo
        
    ThirdPartLoginViewController *viewController = [[ThirdPartLoginViewController alloc] initWithUserInfo:weibo_userInfo_dict platformId:1];
	viewController.delegate = self;
    viewController.pushViewDelegate = self;
        [self.navigationController pushViewController:viewController animated:YES];
        
    }
    
    else if(self.oauthType == 2){ //qq
        ThirdPartLoginViewController *viewController = [[ThirdPartLoginViewController alloc] initWithUserInfo:qq_userInfo_dict platformId:2];
        viewController.delegate = self;
        viewController.pushViewDelegate = self;
	  [self.navigationController pushViewController:viewController animated:YES];
    }
    
    
}


#pragma mark action

- (void)loginSuccess{
    

    CLog(@"Login success!");
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] != nil) {
        
      
        int uid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];
        
        [self loadTimelineMember:uid];
        
    }   
    else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"帐号密码错误！" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
        [alert show];
        [alert release];
        
    }
    
           
}

- (void)loginErrorWith:(NSString *)info
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"失败!" message:@"连接错误，重新连接！" 
                                                   delegate:self 
                                          cancelButtonTitle:@"取消" otherButtonTitles:nil];
       
    [alert show];
    [alert release];
     
}

- (void)loginError{
    
	[self loginErrorWith:@"密码错误或网络连接失败！"];
}


#pragma mark -
#pragma mark 注册页面
-(IBAction)registerNowActon{

    
    RegistViewController *registViewController = [[RegistViewController alloc] init];
	
	[self.navigationController pushViewController:registViewController animated:YES];	
    
    
}

#pragma mark -
#pragma mark UITextView delegate

-(void)textViewDidChange:(UITextView *)textView
{
	
	
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
	
	return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    
    
	
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    
    
	
}


#pragma mark textField delegate




-(IBAction)backgroundTap:(id)sender{
    
    [loginIDtextField resignFirstResponder];
    [loginkeytextField resignFirstResponder];
    
}

#pragma mark load data
//下载可管理的时间轴

-(void)loadTimelineMember:(int)uid{
    
    [LoadingView showDefaultLoadingView];
    
    NSMutableURLRequest * request = [WebRequest userTiemlineMemberRequestWith:[NSString stringWithFormat:@"%d",uid]];
	
	CLog(@"request %@", request);
	timeline_Connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:@"TimelineId"];
    
}


#pragma mark -WebConnection delegate

- (void)connectionArraySuccess:(NSDictionary *)dict connectionURL:(NSString *)url{
    
    
    [LoadingView hideWithAnimated:YES];
    
   
    NSDictionary *dictionary = [dict objectForKey:@"object"];
   
    CLog(@"url %@", url);
    
    //verify token weibo
    
    NSString *weibo_token = [weibo_userInfo_dict objectForKey:@"id"];
    
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/openmobile/verify/token?platformId=%d&accessToken=%@",MYBASEURL, oauthType,weibo_token]])  {
        
        
        if (dictionary != nil) { //已经绑定过 只返回一个uid int
            
            CLog(@"verify dictionary %@", dictionary);
    
            [[NSUserDefaults standardUserDefaults] setValue:[dict objectForKey:@"object"] forKey:@"userId"];
                      //open check
            [self openCheck:weibo_token];
            
            return;
        }
        
        else{ //第三方新用户
            //qq 新用户
            if (oauthType == 1) {
                
                if (weibo_userInfo_dict != nil) {
                    
                    [self loadThirdPartView];
                    // [self createNewQQUser]; 
                }
                
                
            }
            
            
        }
        
        
    }
    

    
    
    
    //verify token qq
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/openmobile/verify/token?platformId=%d&accessToken=%@",MYBASEURL, oauthType,_tencentOAuth.openId]])  {
        
        if (dictionary != nil) { //已经绑定过 只返回一个uid int
            
            CLog(@"verify dictionary %@", dictionary);
            [[NSUserDefaults standardUserDefaults] setValue:[dict objectForKey:@"object"] forKey:@"userId"];
            
            NSString *acessToken = _tencentOAuth.openId;
            
            //open check
            [self openCheck:acessToken];
            
            return;
        }
        
        else{ //第三方新用户
            //qq 新用户
            if (oauthType == 2) {
                
                if (qq_userInfo_dict != nil) {
                    
                    [self loadThirdPartView];
                    // [self createNewQQUser]; 
                }
                 
                
            }
           
            
        }
        
        return;
        
    }
   
       
    
    //新用户绑定
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/openmobile/regist/binding/new",MYBASEURL]]) {//返回 token userid
        
        
        NSString *acessToken = [dictionary objectForKey:@"accessToken"];
        
        //save usre info
        if([[dictionary allKeys] containsObject:@"userId"]){
            
            [[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"userId"] forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults]setValue:[dictionary objectForKey:@"userName"] forKey:@"userName"];
            [[NSUserDefaults standardUserDefaults]setValue:[dictionary objectForKey:@"userAttachmentId"] forKey:@"userAttachmentId"];
        
      //  [self openCheck:acessToken];
        //不用cookie 验证
            [[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"User-Code"] forKey:@"User-Code"];
            [[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"User-VerifyCode"] forKey:@"User-VerifyCode"];
        
        
        //跳到填宝宝信息
            if (self.delegate != nil && [[NSUserDefaults standardUserDefaults] valueForKey:@"userId"]) {
                [self.delegate  toTimelineSettingView:nil];
            }
            
            }
        else{
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"服务器连接错误！" 
                                                           delegate:self 
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            [alert release];
            
        }
        
        return;
        
    }
    
    
    //绑定已有账户
    
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/openmobile/regist/binding/exist",MYBASEURL]]) {//返回 token userid
        
        
        NSString *acessToken = [dictionary objectForKey:@"accessToken"];
        
        // save user info
        [[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"userId"] forKey:@"userId"];
        [[NSUserDefaults standardUserDefaults]setValue:[dictionary objectForKey:@"userName"] forKey:@"userName"];
        [[NSUserDefaults standardUserDefaults]setValue:[dictionary objectForKey:@"userAttachmentId"] forKey:@"userAttachmentId"];
        
               
        //不用cookie 验证
        [[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"User-Code"] forKey:@"User-Code"];
        [[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:@"User-VerifyCode"] forKey:@"User-VerifyCode"];
        
        [self loginSuccess];

        
        return;
        
    }
    

    //可管理时间轴
    
    int userId;
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"]) {
        userId =[[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue]; 
    }

    if ([url isEqualToString:[NSString stringWithFormat:@"%@/mobile/timeline/menu/?uid=%d",MYBASEURL, userId]]) 
    {
        
                
        if ([[dict objectForKey:@"object"] count] >0) {  //保存tid
            
            NSDictionary *timelineDict = [[dict objectForKey:@"object"] objectAtIndex:0];
            
            [[NSUserDefaults standardUserDefaults] setValue:[timelineDict objectForKey:@"id"] forKey:@"timelineId"];
                
                      
        }
        
        //登陆成功
        [self userLoginSuccess];

        
        
    }

   
        
}

- (void)connectionArrayError:(NSError *)error{
	    

    [LoadingView hideWithAnimated:YES];
    self.view.userInteractionEnabled=YES;
    [self loginError];
        
}



- (void)connectionSuccess:(NSDictionary *)dict{
	
	[LoadingView hideWithAnimated:YES];
    
    if (self.oauthType ==0 ) {  //帐号登陆
        
        if(dict){
                  
            //帐号验证
            NSString *state = [dict objectForKey:@"result"];
            if ([state isEqualToString: @"failed"]) {
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"失败!" message:@"帐号密码错误！" 
                                                               delegate:self 
                                                      cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                [alert release];
                
                return;
                
            }
                else{ //登陆成功
                    
                            getUserIdSucced = YES;
                            [[NSUserDefaults standardUserDefaults] setValue:[dict objectForKey:@"userId"] forKey:@"userId"];
                    [[NSUserDefaults standardUserDefaults]setValue:[dict objectForKey:@"userName"] forKey:@"userName"];
                    [[NSUserDefaults standardUserDefaults]setValue:[dict objectForKey:@"userAttachmentId"] forKey:@"userAttachmentId"];
                    
                    [[NSUserDefaults standardUserDefaults] setValue:[dict objectForKey:@"User-Code"] forKey:@"User-Code"];
                     [[NSUserDefaults standardUserDefaults] setValue:[dict objectForKey:@"User-VerifyCode"] forKey:@"User-VerifyCode"];
                    
            
                            [self  loginSuccess];    
                    
                   
            }
            
        }
        
        else{
            [self loginError];
        }
        
    }
    
    
   if(self.oauthType == 2 || self.oauthType == 1) {  //third part 登陆
        
        if(dict){
            
            //帐号验证
            NSString *state = [dict objectForKey:@"result"];
            if ([state isEqualToString: @"failed"]) {
                
                //未绑定的新用户
                [self loadThirdPartView];                
                return;
                
            }
            else{ //登陆成功
                
                getUserIdSucced = YES;
                [[NSUserDefaults standardUserDefaults] setValue:[dict objectForKey:@"userId"] forKey:@"userId"];
                [[NSUserDefaults standardUserDefaults]setValue:[dict objectForKey:@"userName"] forKey:@"userName"];
                [[NSUserDefaults standardUserDefaults]setValue:[dict objectForKey:@"userAttachmentId"] forKey:@"userAttachmentId"];
                               
                [[NSUserDefaults standardUserDefaults] setValue:[dict objectForKey:@"User-Code"] forKey:@"User-Code"];
                [[NSUserDefaults standardUserDefaults] setValue:[dict objectForKey:@"User-VerifyCode"] forKey:@"User-VerifyCode"];
                
                
                [self  loginSuccess];    
                
                
            }
            
        }
        
        else{
            [self loginError];
        }
        
    }
    
   
   	
	CLog(@"login success");
    
}

- (void)connectionError:(NSError *)error{
	CLog(@"error info");
     [LoadingView showDurationMessageLoadingViewWith:10.0 message:@"请求失败，请检查网络连接状态！" ];    self.view.userInteractionEnabled=YES;
    //[self loginError];

    
}
- (void)postSuccess:(NSString *)postinfo{
    
}



-(IBAction)loginAction{
    
    //test   /////////////////////
//    [[NSUserDefaults standardUserDefaults]setValue:[NSNumber numberWithInt:2] forKey:@"userId"];
//    [self loginSuccess];
//    return;
    
    
	
    [self backgroundTap:nil];
    
    if (loginkeytextField.text == @"") {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"密码不能为空" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        return;

    }
   
    if (loginIDtextField.text == @"") {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"帐号不能为空" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        return;
        
    }
    

    
    [LoadingView showDefaultLoadingView];
    
    
  //check  安全验证
    
//    NSMutableURLRequest *request = [RequestAPIExample logginRequestWithUsr:loginIDtextField.text pwd:loginkeytextField.text];
//    [request setHTTPShouldHandleCookies:YES];
//    [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    
    
    [[NSUserDefaults standardUserDefaults] setValue:loginIDtextField.text forKey:@"email"];
    
    //不验证，直接用帐号登陆获取
    self.oauthType = 0;
   
    NSArray *keys = [NSArray arrayWithObjects:@"pass", @"email",@"loginType", nil];
    
    
    NSArray *objects = [NSArray arrayWithObjects:loginkeytextField.text, loginIDtextField.text,@"growth", nil];
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    CLog(@"theBodyString  %@", theBodyString);
    
    //   	
    NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
    //	
    NSMutableURLRequest * request = [WebRequest LoginRequestWith:_jsonData];
   
   loginConnection = [[WebConnection alloc] initWith:request delegate:self dataBaseListName:nil];
    

    
    
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    if (self.oauthType != 0) { // 非帐号登陆
        
               
        NSDictionary *headerFields = [response allHeaderFields]; 
        
        NSURL *url = response.URL;  
        
        NSHTTPCookie *cookie = [[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url] objectAtIndex:0] ;
        NSString *session = [NSString stringWithFormat:@"%@=%@",[cookie name],[cookie value]];
        CLog(@"seesion %@", session);
        
        //保存cookie
        [[NSUserDefaults standardUserDefaults] setValue:session forKey:@"cookie"];
        

        [self loginSuccess];
        
        return;
        
        
    }
    
    
    //帐号登陆
    
    NSDictionary *headerFields = [response allHeaderFields]; 
    
    NSURL *url = connection.originalRequest.URL;  
    
    CLog(@"login check URL %@", url);
    
    CLog(@"login check headerField %@",headerFields);
    
    CLog(@"login check cookie %@", [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url]);
    
    NSHTTPCookie *cookie = [[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url] objectAtIndex:0] ;
    NSString *session = [NSString stringWithFormat:@"%@=%@",[cookie name],[cookie value]];
    CLog(@"seesion %@", session);
    
    
    [[NSUserDefaults standardUserDefaults] setValue:session forKey:@"cookie"];
    
    /////log in post
    
    NSArray *keys = [NSArray arrayWithObjects:@"pass", @"email", nil];
    
    
    NSArray *objects = [NSArray arrayWithObjects:loginkeytextField.text, loginIDtextField.text, nil];
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    CLog(@"theBodyString  %@", theBodyString);
    
    //   	
    NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
    //	
    NSMutableURLRequest * request = [WebRequest LoginRequestWith:_jsonData];
    //	
    //     
    //	CLog(@"request %@", request);
    WebConnection *loginConnection = [[WebConnection alloc] initWith:request delegate:self dataBaseListName:nil];
    
	
}

-(IBAction)QQ2loginAction{
    
    self.oauthType =   2; //qq login
    
    _permissions =  [[NSArray arrayWithObjects:
					  @"get_user_info",@"add_share", @"add_topic",@"add_one_blog", @"list_album", 
					  @"upload_pic",@"list_photo", @"add_album", @"check_page_fans",nil] retain];
	
	
	_tencentOAuth = [[TencentOAuth alloc] initWithAppId:@"100260065"
											andDelegate:self];
	_tencentOAuth.redirectURI = @"www.qq.com";
    
    _tencentOAuth.accessToken = [[NSUserDefaults standardUserDefaults] valueForKey:QQAccessToken];
    _tencentOAuth.expirationDate = [[NSUserDefaults standardUserDefaults] valueForKey:QQExpirationDate];
    _tencentOAuth.openId = [[NSUserDefaults standardUserDefaults] valueForKey:QQOpenId];
    [_tencentOAuth authorize:_permissions inSafari:NO];
    
}


/**
 * Called when the user successfully logged in.
 */
- (void)tencentDidLogin {
	// 登录成功
#pragma mark HOBO
    //在这里直接调用UserInfo即可获取用户信息
    
    [self onClickGetUserInfo];
    
		
	
}


- (void)onClickGetUserInfo {

	[_tencentOAuth getUserInfo];
}

/**
 * Called when the user dismissed the dialog without logging in.
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
		
}

/**
 * Called when the notNewWork.
 */
-(void)tencentDidNotNetWork
{
	}
/**
 * Called when the get_user_info has response.
 */
- (void)getUserInfoResponse:(APIResponse*) response {
    
#pragma mark HOBO
    //这里是获取用户信息成功的用户信息
	if (response.retCode == URLREQUEST_SUCCEED)
	{
		
		
		NSMutableString *str=[NSMutableString stringWithFormat:@""];		
		for (id key in response.jsonResponse) {			
			[str appendString: [NSString stringWithFormat:@"%@:%@\n",key,[response.jsonResponse objectForKey:key]]];
		}
        
        self.qq_userInfo_dict = response.jsonResponse;
        
        //qq 信息成功
        //verify qq token
        
       // [self verifyToken];
      //直接用login 接口
        NSArray *keys = [NSArray arrayWithObjects:@"token", @"platformId", nil];
        
        
        NSArray *objects = [NSArray arrayWithObjects:_tencentOAuth.openId, [NSNumber numberWithInt:2], nil];
        NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
        
        NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
        CLog(@"theBodyString  %@", theBodyString);
        
        //   	
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        //	
        NSMutableURLRequest * request = [WebRequest LoginRequestWith:_jsonData];
        
        WebConnection *loginConnection = [[WebConnection alloc] initWith:request delegate:self dataBaseListName:nil];
      	

        
	}
	else {

	}
	
    
    [[NSUserDefaults standardUserDefaults] setValue:_tencentOAuth.accessToken forKey:QQAccessToken];
    [[NSUserDefaults standardUserDefaults] setValue:_tencentOAuth.expirationDate forKey:QQExpirationDate];
    [[NSUserDefaults standardUserDefaults] setValue:_tencentOAuth.openId forKey:QQOpenId];
    
    NSLog(@"AccessToken %@", _tencentOAuth.accessToken);
    NSLog(@"ExpirationDate %@", _tencentOAuth.expirationDate);
    NSLog(@"OpenId %@", _tencentOAuth.openId);
}

/**
 * Called when the add_share has response.
 */
- (void)addShareResponse:(APIResponse*) response {
	if (response.retCode == URLREQUEST_SUCCEED)
	{
		
		
		NSMutableString *str=[NSMutableString stringWithFormat:@""];		
		for (id key in response.jsonResponse) {			
			[str appendString: [NSString stringWithFormat:@"%@:%@\n",key,[response.jsonResponse objectForKey:key]]];
		}
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作成功" message:[NSString stringWithFormat:@"%@",str]
							  
													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles:nil];
		[alert show];
		
		
		
	}
	else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作失败" message:[NSString stringWithFormat:@"%", response.errorMsg]
							  
													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles: nil];
		[alert show];
	}
	
	
	
}





///////////////////////////////////////////////////////////////////////////////////////////////////

//TencentRequestDelegate

/**
 * Handle the auth.ExpireSession api call failure
 */
- (void)request:(TencentRequest*)request didFailWithError:(NSError*)error{
	//NSString *errorInfo = [error localizedDescription];
	NSLog(@"Failed to expire the session");
}

- (void)request:(TencentRequest *)request didReceiveResponse:(NSURLResponse *)response {
	NSLog(@"received response");
}



/**
 * Called when a request returns and its response has been parsed into
 * an object. The resulting object may be a dictionary, an array, a string,
 * or a number, depending on the format of the API response. If you need access
 * to the raw response, use:
 *
 * (void)request:(FBRequest *)request
 *      didReceiveResponse:(NSURLResponse *)response
 */
- (void)request:(TencentRequest *)request didLoad:(id)result dat:(NSData *)data{
	if ([result isKindOfClass:[NSDictionary class]]) {
		NSDictionary *root = (NSDictionary *)result;
		if ([[root allKeys] count] == 0) {
			NSLog(@"received didLoad error");
			return;
		}
	}
};

//wei bo  third part
-(IBAction)weiboLoginAction{
    
    
    self.oauthType = 1;
    WBEngine *engine = [[WBEngine alloc] initWithAppKey:kWBSDKDemoAppKey appSecret:kWBSDKDemoAppSecret];
    [engine setRootViewController:self];
    [engine setDelegate:self];
    //[engine setRedirectURI:@"http://"];
    [engine setRedirectURI:@"http://www.meetmama.com"];
    [engine setIsUserExclusive:NO];
    self.weiBoEngine = engine;
    [engine release];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];

    [weiBoEngine logIn];
    
}


- (void)engineDidLogIn:(WBEngine *)engine
{
   
//    UIAlertView* alertView = [[UIAlertView alloc]initWithTitle:nil 
//													   message:@"登录成功！" 
//													  delegate:self
//											 cancelButtonTitle:@"确定" 
//											 otherButtonTitles:nil];
//    [alertView setTag:kWBAlertViewLogInTag];
//	[alertView show];
//	[alertView release];
    
    //微博登陆成功
    //取用户信息
    
    NSLog(@"UID Did Login %@", weiBoEngine.userID);
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setValue:weiBoEngine.userID forKey:@"uid"];
    
    [weiBoEngine loadRequestWithMethodName:@"users/show.json"
                                httpMethod:@"GET"
                                    params:dict
                              postDataType:kWBRequestPostDataTypeNormal
                          httpHeaderFields:nil];

    
}

#pragma mark - UIAlertViewDelegate Methods

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == kWBAlertViewLogInTag)
    {
        
        //取用户信息
        
        NSLog(@"UID Did Login %@", weiBoEngine.userID);
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setValue:weiBoEngine.userID forKey:@"uid"];
        
        [weiBoEngine loadRequestWithMethodName:@"users/show.json"
                                    httpMethod:@"GET"
                                        params:dict
                                  postDataType:kWBRequestPostDataTypeNormal
                              httpHeaderFields:nil];
        
        return;

        
        
    }
    else if (alertView.tag == kWBAlertViewLogOutTag)
    {
       
    }
}

- (void)engine:(WBEngine *)engine didFailToLogInWithError:(NSError *)error
{
   
  
    UIAlertView* alertView = [[UIAlertView alloc]initWithTitle:nil 
													   message:@"登录失败！" 
													  delegate:nil
											 cancelButtonTitle:@"确定" 
											 otherButtonTitles:nil];
	[alertView show];
	[alertView release];
}



#pragma mark - WBEngineDelegate Methods

//user info
- (void)engine:(WBEngine *)engine requestDidSucceedWithResult:(id)result
{
    
    //NSLog(@"requestDidSucceedWithResult: %@", result);
    if ([result isKindOfClass:[NSDictionary class]])
    {
        NSLog(@"User Info %@", result);
        
        self.weibo_userInfo_dict = result;
       // [self verifyToken];
        //直接用login 接口
         NSString *weibo_token = [weibo_userInfo_dict objectForKey:@"id"];
        
        NSArray *keys = [NSArray arrayWithObjects:@"token", @"platformId", nil];
        
        
        NSArray *objects = [NSArray arrayWithObjects:weibo_token, [NSNumber numberWithInt:1], nil];
        NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
        
        NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
        CLog(@"theBodyString  %@", theBodyString);
        
        //   	
        NSData *_jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
        //	
        NSMutableURLRequest * request = [WebRequest LoginRequestWith:_jsonData];
        
        WebConnection *loginConnection = [[WebConnection alloc] initWith:request delegate:self dataBaseListName:nil];
      	
        
    }
}

- (void)engine:(WBEngine *)engine requestDidFailWithError:(NSError *)error
{
  
    NSLog(@"requestDidFailWithError: %@", error);
}


-(void)dealloc{
    
    
    
    [backGroundButton release];
    
    if (loginConnection != nil) {
        loginConnection.connectionDelegate = nil;
        [loginConnection release];
    }
    
    if (timeline_Connection != nil) {
        timeline_Connection.connectionDelegate = nil;
        [timeline_Connection release];
    }
    
    
    if (createNewUser_Connection != nil) {
        createNewUser_Connection.connectionDelegate = nil;
        [createNewUser_Connection release];
    }
    
    if (bindUser_Connection != nil) {
        bindUser_Connection.connectionDelegate = nil;
        [bindUser_Connection release];
    }
    
    [loginIDtextField release];
    [loginkeytextField release];
    [qq_userInfo_dict release];
    [weiBoEngine release];
    [weibo_userInfo_dict release];
    [super dealloc];
    
}


#pragma mark textField delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
           [textField resignFirstResponder];
    
    
    return YES;
}


#pragma mark - User loggin success  登陆成功
- (void)userLoginSuccess{
    
    //数据统计
    [MobClick event:@"login" label:VERSION];
    
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:1] forKey:@"isFirstInApp"];
    
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] != nil) {
        
        if (self.delegate != nil) {
            [self.delegate reloadData];
        }
        
        [self.navigationController dismissModalViewControllerAnimated:YES];
        
        
    }
    
    
}




#pragma mark -
#pragma mark UINavigateBar
- (void)navigationBarInit
{
    
        
    //定义右侧按钮
    //    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
    //    [rightButton addTarget:self action:@selector(postRecordAction:) forControlEvents:UIControlEventTouchUpInside];
    //    
    //    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    //    [rightButton release];
    
     //定义左侧按钮
    //    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
    //    [leftButton setImage:[UIImage imageNamed:@"bt_more_iphone.png"] forState:UIControlStateNormal];
    //    [leftButton setImage:[UIImage imageNamed:@"bt_jihua_iphone.png"] forState:UIControlStateSelected];
    //    [leftButton addTarget:self action:@selector(dismissModalAction:) forControlEvents:UIControlEventTouchUpInside];
    //    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    //    [leftButton release];
    
      
      
    //iOS 5.0 Top bar效果优化
    double sysVersion = [[[UIDevice currentDevice] systemVersion] doubleValue];
    if (sysVersion >= 5.0) {
        CLog(@"ios 5 top bar");
        
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bgtopbar_zhujiemian_iphone.png"] forBarMetrics:UIBarMetricsDefault];
    }
    [self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:44.0 /255.0 green:136.0  /255.0 blue:35.0  /255.0 alpha:1]];
    
}


@end
